package com.ad.aidai.fragments.me.profile.update_personal_note;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 修改个性签名页面
 * Created by pure on 2017/2/4.
 */

public class UpPersonalNoteFragment extends BaseFragment implements UpPersonalNoteContract.View{
    @BindView(R.id.et_order_content)
    EditText etOrderContent;
    @BindView(R.id.tv_num)
    TextView tvNum;

    private UpPersonalNoteContract.Presenter mPresenter;

    private LoadingDialog loadingDialog;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_update_personal_note, container, false);
        mView.setClickable(true);//防止点击穿透，底层的fragment响应上层点击触摸事件

    }

    @Override
    protected void initView() {
        //对于刚跳到一个新的界面就要弹出软键盘的情况上述代码可能由于界面为加载完全而无法弹出软键盘。
        //此时应该适当的延迟弹出软键盘如998毫秒（保证界面的数据加载完成）
        etOrderContent.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){
            @Override
            public void run(){
                openSoftInput(etOrderContent);
            }
        }, 500);

    }

    @Override
    protected void initData() {
        new UpPersonalNotePresenter(mContext, this).subscribe();
        etOrderContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvNum.setText(s.length() + "/30");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        String note=getArguments().getString("personal_note");
        etOrderContent.setText(note);

    }

    @Override
    public void modifySuccess() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog.isShowing()) {

                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeSoftInput(etOrderContent);
                        getFragmentManager().popBackStack();
                    }
                });
            }
        }).start();
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mActivity);
        loadingDialog.setLoadingText("修改中...")
                .setFailedText("修改失败")
                .setSuccessText("修改成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void setPresenter(UpPersonalNoteContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @OnClick({R.id.iv_back,R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                closeSoftInput(etOrderContent);
                onActivityBackPressed();
                break;
            case R.id.tv_submit:
                mPresenter.savePerSignature(etOrderContent.getText().toString());
                break;
        }
    }

    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 弹出软键盘
     *
     * @param view 对应的EditText
     */
    public void openSoftInput(View view){
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, 0);
//        inputManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);//用这个也可以
    }

    @Override
    public boolean onActivityBackPressed() {
        getFragmentManager().popBackStack();
        return false;
    }
}
